import store from '@/store'

export function setDomainValue(domain, value) {
  let rootValue = store.getters['pageSettings']
  var v = _setDomainValue(domain.split('.'), value, rootValue);
  store.dispatch('settings/setPageSettings', v)
}

export function getDomainValue(value, domain, defaultVal) {
  return _getDomainValue(value, domain.split('.'), defaultVal);
}

function _setDomainValue(domain, value, rootValue) {
  var key = domain;
  if (Array.isArray(domain)) {
    key = domain[0];
    if (domain.length > 1) {
      let d = domain.splice(1)
      let rv = rootValue[key]
      if (rv == undefined) {
        rv = {}
      }
      value = _setDomainValue(d, value, rv);
    }
  }
  rootValue[key] = value;
  return rootValue;
}

function _getDomainValue(value, domain, defaultVal) {
  if (Array.isArray(domain)) {
    value = value[domain[0]];
    if (domain.length == 1 || !value) {
      return value || defaultVal;
    }
    return _getDomainValue(value, domain.splice(1), defaultVal);
  }
  return value[domain] || defaultVal;
}
